using System.Windows.Input;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using AFEParserWPF.Models;
using AFEParserWPF.Services;

namespace AFEParserWPF.ViewModels;

/// <summary>
/// 使用 MVVM Community Toolkit 的主窗口 ViewModel
/// </summary>
public partial class MainWindowViewModel : ObservableObject
{
    private readonly AFEParser _afeParser = new();
    
    [ObservableProperty]
    private string filePath = "";

    [ObservableProperty]
    private string reportOutput = "加载 AFE 二进制文件以查看报告...";

    [ObservableProperty]
    private string statusMessage = "就绪";

    [ObservableProperty]
    private bool isLoading = false;

    [RelayCommand]
    public async Task BrowseFile()
    {
        var dialog = new Microsoft.Win32.OpenFileDialog
        {
            Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*",
            Title = "Select AFE Report File"
        };

        if (dialog.ShowDialog() == true)
        {
            FilePath = dialog.FileName;
            await ParseFile();
        }
    }

    [RelayCommand]
    public async Task ParseFile()
    {
        if (string.IsNullOrWhiteSpace(FilePath))
        {
            StatusMessage = "错误：请先选择文件";
            return;
        }

        if (!File.Exists(FilePath))
        {
            StatusMessage = "错误：文件不存在";
            return;
        }

        try
        {
            IsLoading = true;
            StatusMessage = "正在解析文件...";
            
            object? result = await Task.Run(() => AFEParser.ParseFile(FilePath));
            string report = FormatReport(result);
            
            ReportOutput = report;
            StatusMessage = "文件解析成功";
        }
        catch (Exception ex)
        {
            ReportOutput = $"Error: {ex.Message}";
            StatusMessage = $"错误：{ex.Message}";
        }
        finally
        {
            IsLoading = false;
        }
    }

    [RelayCommand]
    public void HandleDrop(System.Windows.IDataObject dataObject)
    {
        if (dataObject.GetDataPresent(System.Windows.DataFormats.FileDrop))
        {
            var files = (string[]?)dataObject.GetData(System.Windows.DataFormats.FileDrop);
            if (files?.Length > 0)
            {
                FilePath = files[0];
                ParseFileCommand.Execute(null);
            }
        }
    }

    [RelayCommand]
    public void CopyToClipboard()
    {
        if (!string.IsNullOrEmpty(ReportOutput))
        {
            System.Windows.Clipboard.SetText(ReportOutput);
            StatusMessage = "报告已复制到剪贴板";
        }
    }

    [RelayCommand]
    public void SaveReport()
    {
        if (string.IsNullOrEmpty(ReportOutput) || ReportOutput.StartsWith("错误"))
        {
            StatusMessage = "没有内容可保存";
            return;
        }

        try
        {
            var dialog = new Microsoft.Win32.SaveFileDialog
            {
                Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
                FileName = $"AFE_Report_{DateTime.Now:yyyyMMdd_HHmmss}.txt"
            };

            if (dialog.ShowDialog() == true)
            {
                File.WriteAllText(dialog.FileName, ReportOutput);
                StatusMessage = $"已保存到：{dialog.FileName}";
            }
        }
        catch (Exception ex)
        {
            StatusMessage = $"保存失败：{ex.Message}";
        }
    }

    private static string FormatReport(object? result)
    {
        return result switch
        {
            AtmosphereFatalErrorCtx ctx => ReportFormatter.FormatAFE2Report(ctx),
            AtmosphereFatalErrorCtx1 ctx => ReportFormatter.FormatAFE1Report(ctx),
            AtmosphereFatalErrorCtx0 ctx => ReportFormatter.FormatAFE0Report(ctx),
            _ => "错误：不支持的或无效的 AFE 文件格式"
        };
    }
}
